// lib/controllers/buy_conditions_controller.dart
import 'package:get/get.dart';
import '../../../data/datasource/local/database.dart';

class BuyConditionsController extends GetxController {
  final AppDatabase database = Get.find<AppDatabase>();

  final RxList<BuyCondition> buyConditions = <BuyCondition>[].obs;
  final RxBool isLoading = false.obs;
  final Rx<BuyCondition?> selectedCondition = Rx<BuyCondition?>(null);
  final RxBool isEditing = false.obs;

  @override
  void onInit() {
    super.onInit();
    loadBuyConditions();
  }

  Future<void> loadBuyConditions() async {
    isLoading.value = true;
    try {
      final conditions = await database.allBuyConditions;
      buyConditions.assignAll(conditions);
    } catch (e) {
      Get.snackbar('错误', '加载买入条件失败: $e');
    } finally {
      isLoading.value = false;
    }
  }

  // 在 BuyConditionsController 中更新方法
  Future<void> addBuyCondition(BuyConditionsCompanion companion) async {
    try {
      await database.into(database.buyConditions).insert(companion);
      // 移除这里的Get.snackbar
      loadBuyConditions(); // 重新加载列表
    } catch (e) {
      // 移除这里的Get.snackbar，改为抛出异常
      throw e;
    }
  }

  Future<void> updateBuyCondition(BuyCondition condition) async {
    try {
      await database.update(database.buyConditions).replace(condition);
      // 移除这里的Get.snackbar
      loadBuyConditions(); // 重新加载列表
    } catch (e) {
      // 移除这里的Get.snackbar，改为抛出异常
      throw e;
    }
  }

  Future<void> deleteBuyCondition(int id) async {
    try {
      await (database.delete(database.buyConditions)..where((t) => t.id.equals(id))).go();
      Get.snackbar('成功', '删除买入条件成功');
      loadBuyConditions(); // 重新加载列表
    } catch (e) {
      Get.snackbar('错误', '删除买入条件失败: $e');
    }
  }

  void setEditingCondition(BuyCondition? condition) {
    selectedCondition.value = condition;
    isEditing.value = condition != null;
  }

  void clearEditing() {
    selectedCondition.value = null;
    isEditing.value = false;
  }
}